﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
//using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Diagnostics;


namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private SqlConnection conn = new SqlConnection();
        public DataTable dt_drugs;
        public DataTable dt_brand;
        public DataTable dt_suppl;
        public DataTable dt_pharm;
        public DataTable dt_drug_tmp;
        public DataTable dt_rep = new DataTable();
        private const string namechcol = "Флаг";
        private Guid guid;
        private delegate void Deleg();
        private Deleg del;
        private bool showres = true;

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DrugsFilter.DrugsFilter f2 = new DrugsFilter.DrugsFilter();
            DrugsFilter.DrugsFilter.StorProcParam[] spp = new DrugsFilter.DrugsFilter.StorProcParam[1];

            spp[0] = f2.StorProcParamIns("@arch", SqlDbType.VarChar, 20, "jhjhjh");

            SqlCommand myCommand = new SqlCommand();
            myCommand = f2.StorProc(myCommand, conn, "pas_AllDrugsSel", spp);

            if (dt_drugs == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drugs = new DataTable();
                    dt_drugs.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drugs.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    //dt_brand = new DataTable();
                    //dt_brand.Load(GetBrandTree(conn));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
                f2.rb = true;
            }
            if (dt_drug_tmp == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drug_tmp = new DataTable();
                    dt_drug_tmp.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drug_tmp.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
            }
            f2.sqlconn = conn;
            f2.namechcol = namechcol;
            f2.dt_drug = dt_drugs;
            f2.dt_drug_tmp = dt_drug_tmp;
            if (dt_drug_tmp.Rows.Count == 0)
                f2.dataGridView1.DataSource = f2.dt_drug.DefaultView;
            else
                f2.dataGridView1.DataSource = f2.dt_drug_tmp.DefaultView;
            f2.dt_br = dt_brand;
            f2.ShowDialog();
            listBox1.Items.Clear();
            foreach (DataRow dr in dt_drug_tmp.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true && dr.RowState != DataRowState.Deleted)
                {
                    listBox1.Items.Add(dr["Товар"]);
                }
            }
            if (listBox1.Items.Count == 0) listBox1.Items.Add("(Все товары)");
            f2.Close();

        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn.ConnectionString = @"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True";
            listBox1.Items.Add("(Все товары)");
            listBox3.Items.Add("(Все аптеки)");
            guid = Guid.NewGuid();
            dataGridView1.DataSource = dt_rep.DefaultView;
            dateTimePicker1.Value = DateTime.Now.Date;
            dateTimePicker2.Value = DateTime.Now.Date.AddDays(180);

            DataTable dt_az = new DataTable();
            dt_az = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_StatusSel", 30, null);
            checkedListBox1.Items.Clear();
            foreach (DataRow row in dt_az.Rows)
            {
                NewItem ni = new NewItem();
                ni.ParamID = row[0];
                ni.ParamComment = row[2].ToString();
                checkedListBox1.Items.Add(ni);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
            
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            if (showres)
            {
                dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));                
            }
            else MessageBox.Show("Отчет сформирован");
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                DataTable drcode = new DataTable();
                DataTable drpharm = new DataTable();
                DataTable az = new DataTable();

                drcode.Columns.Add();
                drpharm.Columns.Add();
                az.Columns.Add();

                if(dt_drug_tmp != null)
                    if (dt_drug_tmp.Rows.Count > 0)
                    {
                        foreach (DataRow row in dt_drug_tmp.Rows)
                            if (Convert.ToBoolean(row[0]))
                            {
                                drcode.Rows.Add(new object[1] { row[1] });
                            }
                    }

                if(dt_pharm != null)
                    if (dt_pharm.Rows.Count > 0)
                    {
                        foreach (DataRow row in dt_pharm.Rows)
                            if (Convert.ToBoolean(row[0]))
                            {
                                drpharm.Rows.Add(new object[1] { row[1] });
                            }
                    }

                if (checkedListBox1.Items.Count > 0)
                {
                    if(checkedListBox1.CheckedItems.Count > 0)
                    for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
                    {
                        az.Rows.Add((checkedListBox1.CheckedItems[i] as NewItem).ParamID);
                    }
                }
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[5];
                par[0].name = "@drugcode";
                par[0].value = drcode;
                par[1].name = "@pharmcode";
                par[1].value = drpharm;
                par[2].name = "@az_stat";
                par[2].value = az;
                par[3].name = "@datebeg";
                par[3].value = dateTimePicker1.Value.Date;
                par[4].name = "@dateend";
                par[4].value = dateTimePicker2.Value.Date;

                dt_rep.Clear();
                dt_rep = new DataTable();
                dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_DAC_BestBeforeDay", 600, par);
 
                //conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                //conn.Close();
            }
        }



        private SqlDataReader GetBrandTree(SqlConnection sqlcon)
        {
            SqlCommand com = sqlcon.CreateCommand();
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = @"pas_BrandTreeSel";

            return com.ExecuteReader();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                PharmFilter.PharmFilter f3 = new PharmFilter.PharmFilter();

                if (dt_pharm == null)
                {
                    SqlCommand myCommand = conn.CreateCommand();
                    myCommand.CommandType = CommandType.StoredProcedure;
                    myCommand.CommandText = @"pas_PharmSel";
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_pharm = new DataTable();
                    dt_pharm.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_pharm.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    conn.Close();
                }
                f3.namechcol = namechcol;
                f3.Text = "Фильтр по аптекам";
                f3.sortcoumn = "Аптека";
                f3.dataGridView1.DataSource = dt_pharm.DefaultView;
                f3.ShowDialog();
                listBox3.Items.Clear();
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]) == true) listBox3.Items.Add(dr[f3.sortcoumn]);
                }
                if (listBox3.Items.Count == 0) listBox3.Items.Add("(Все аптеки)");
                f3.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "сроки годности";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if ((new ExpToExcel()).SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, false))
                    MessageBox.Show("Файл сохранен");
            }
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            if (dateTimePicker2.Value <= dateTimePicker1.Value) dateTimePicker1.Value = dateTimePicker2.Value;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if (dateTimePicker2.Value <= dateTimePicker1.Value) dateTimePicker2.Value = dateTimePicker1.Value;
        }

    }
}
